package com.seeyon.apps.seepkk.manager;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import jersey.repackaged.com.google.common.collect.Maps;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.BaseManager;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.apps.kk.util.WordToPDF;
import com.seeyon.apps.seepkk.util.DesUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.dao.EnumItemDAO;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.util.DBAgent;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.oainterface.impl.exportdata.FileDownloadExporter;
import com.seeyon.oainterface.impl.exportdata.FileUploadExporter;

public class SeepManager extends BaseManager {
    private static final Log log = LogFactory.getLog(SeepManager.class);
    private FreemarkFlowManager freemarkFlowManager;
    private FormDataBaseManager kkBaseFormManager;
    private AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
    private FileManager fileManager = (FileManager) AppContext.getBean("fileManager");
    private AttachmentDAO attachmentDAO = (AttachmentDAO) AppContext.getBean("attachmentDAO");
    private EnumItemDAO enumItemDAO = (EnumItemDAO) AppContext.getBean("newEnumItemDAO");
    private FormApi4Cap4 formApi4Cap4;
    private String mdmKey;
    private QiangsSeepManager qiangsSeepManager;


    public void setQiangsSeepManager(QiangsSeepManager qiangsSeepManager) {
        this.qiangsSeepManager = qiangsSeepManager;
    }

    public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
        this.kkBaseFormManager = kkBaseFormManager;
    }

    /**
     * 会议日程时间重复校验
     */
    public String meetingCheck(Map<String, Object> formdata) {
        String result = "";
        List<String> startDateList = new ArrayList<String>();
        List<String> endDateList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        List<Integer> sortList = new ArrayList<Integer>();
        try {
            startDateList = (List<String>) formdata.get("会议开始时间");
            endDateList = (List<String>) formdata.get("会议结束时间");
            nameList = (List<String>) formdata.get("提供者编号");
            sortList = (List<Integer>) formdata.get("会议日程序号");
            for (int i = 0; i < startDateList.size(); i++) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                //当前行会议开始时间
                Date nowRowStatDate = format.parse(startDateList.get(i).toString());
                //当前行会议结束时间
                Date nowRowEndDate = format.parse(endDateList.get(i).toString());
                //当前行会议提供者
                String name = nameList.get(i);
                if (name == null) {
                    continue;
                }
                for (int j = 0; j < startDateList.size(); j++) {
                    Date startDateRow = format.parse(startDateList.get(j).toString());
                    Date endDateRow = format.parse(endDateList.get(j).toString());
                    String nameRow = nameList.get(j);
                    Object sortRow = sortList.get(j);
                    if (i != j && name.equals(nameRow)) {
                        //会议时间重复校验
                        if ((nowRowStatDate.getTime() > startDateRow.getTime() && nowRowStatDate.getTime() < endDateRow.getTime()) || (nowRowEndDate.getTime() > startDateRow.getTime() && nowRowEndDate.getTime() < endDateRow.getTime())) {
                            result = "该人员在该时间段内已有会议，不能重复参加！重复数据第" + sortRow + "行";
                            return result;
                        }
                        if (nowRowStatDate.getTime() <= startDateRow.getTime() && nowRowEndDate.getTime() >= endDateRow.getTime()) {
                            result = "该人员在该时间段内已有会议，不能重复参加！重复数据第" + sortRow + "行";
                            return result;
                        }
                    }
                }

            }
        } catch (Exception e) {
            log.error("seepkk-会议日程时间校验异常:", e);
            log.error("seepkk-会议日程开始时间:" + startDateList);
            log.error("seepkk-会议日程结束时间:" + endDateList);
            log.error("seepkk-会议日程提供者:" + nameList);
            result = "会议日程时间校验异常-人员校验！";
            return result;
        }
        return result;
    }


    /**
     * 会议日程时间连续性校验，同一人，同一天时间填写时要连续
     */
    public String meetingTimeCheck(Map<String, Object> formdata) {
        String result = "";
        List<String> startDateList = new ArrayList<String>();
        List<String> endDateList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        List<String> nameZHList = new ArrayList<String>();
        try {
            startDateList = (List<String>) formdata.get("会议开始时间");
            endDateList = (List<String>) formdata.get("会议结束时间");
            nameList = (List<String>) formdata.get("提供者编号");
            nameZHList = (List<String>) formdata.get("提供者");
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < startDateList.size(); i++) {
                if (nameList.get(i) == null) {
                    continue;
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startDate", startDateList.get(i));
                map.put("endDate", endDateList.get(i));
                map.put("name", nameList.get(i));
                map.put("nameZH", nameZHList.get(i));
                list.add(map);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            list = list.stream().sorted((a, b) -> {
                try {
                    return format.parse(MapUtils.getString(a, "startDate")).compareTo(format.parse(MapUtils.getString(b, "startDate")));
                } catch (Exception e) {
                    return 1;
                }
            }).collect(Collectors.toList());
            Map<Object, List<Map<String, Object>>> dateMap = list.stream().collect(Collectors.groupingBy(t -> MapUtils.getString(t, "name")));
            for (Map.Entry<Object, List<Map<String, Object>>> entry : dateMap.entrySet()) {
                List<Map<String, Object>> dateList = entry.getValue();
                //判断会议开始时间是否等于上次结束时间
                for (int i = 1; i < dateList.size(); i++) {
                    if ((!dateList.get(i).get("startDate").equals(dateList.get(i - 1).get("endDate"))) &&
                            StringUtils.substring(MapUtils.getString(dateList.get(i), "startDate"), 0, 10).equals(StringUtils.substring(MapUtils.getString(dateList.get(i - 1), "endDate"), 0, 10))) {
                        return "同一人员的会议时间必须连续性填写，校验出错人员:" + dateList.get(i).get("nameZH");
                    }
                }
            }

        } catch (Exception e) {
            log.error("seepkk-会议日程时间连续性校验异常:", e);
            log.error("seepkk-会议日程时间连续性校验异常:" + startDateList);
            log.error("seepkk-会议日程时间连续性校验异常:" + endDateList);
            log.error("seepkk-会议日程时间连续性校验异常:" + nameList);
            result = "会议日程时间连续性校验异常！";
            return result;
        }
        return result;
    }

    /**
     * 会议日程时间连续性校验，同一会场时间填写时要连续
     */
    public String meetingPlaceTimeCheck(Map<String, Object> formdata) {
        String result = "";
        List<String> startDateList = new ArrayList<String>();
        List<String> endDateList = new ArrayList<String>();
        List<String> placeList = new ArrayList<String>();
        List<String> sortList = new ArrayList<String>();
        try {
            startDateList = (List<String>) formdata.get("会议开始时间");
            endDateList = (List<String>) formdata.get("会议结束时间");
            placeList = (List<String>) formdata.get("会议会场");
            sortList = (List<String>) formdata.get("会议日程序号");
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < startDateList.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startDate", startDateList.get(i));
                map.put("endDate", endDateList.get(i));
                map.put("name", placeList.get(i));
                map.put("sort", sortList.get(i));
                list.add(map);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            list = list.stream().sorted((a, b) -> {
                try {
                    return format.parse(MapUtils.getString(a, "startDate")).compareTo(format.parse(MapUtils.getString(b, "startDate")));
                } catch (Exception e) {
                    return 1;
                }
            }).collect(Collectors.toList());
            Map<Object, List<Map<String, Object>>> dateMap = list.stream().collect(Collectors.groupingBy(t -> MapUtils.getString(t, "name")));
            for (Map.Entry<Object, List<Map<String, Object>>> entry : dateMap.entrySet()) {
                List<Map<String, Object>> palceCheck = new ArrayList<Map<String, Object>>();
                List<Map<String, Object>> dateList = entry.getValue();
                Map<Object, List<Map<String, Object>>> palceMap = dateList.stream().collect(Collectors.groupingBy(t -> MapUtils.getString(t, "startDate")));
                for (Map.Entry<Object, List<Map<String, Object>>> entry2 : palceMap.entrySet()) {
                    palceCheck.add(entry2.getValue().get(0));
                }
                palceCheck = palceCheck.stream().sorted((a, b) -> {
                    try {
                        return format.parse(MapUtils.getString(a, "startDate")).compareTo(format.parse(MapUtils.getString(b, "startDate")));
                    } catch (Exception e) {
                        return 1;
                    }
                }).collect(Collectors.toList());
                for (int i = 1; i < palceCheck.size(); i++) {
                    if ((!palceCheck.get(i).get("startDate").equals(palceCheck.get(i - 1).get("endDate"))) &&
                            StringUtils.substring(MapUtils.getString(palceCheck.get(i), "startDate"), 0, 10).equals(StringUtils.substring(MapUtils.getString(palceCheck.get(i - 1), "endDate"), 0, 10))) {
                        EnumItemDAO enumItemDAO = (EnumItemDAO) AppContext.getBean("newEnumItemDAO");
                        String placename = enumItemDAO.findById(Long.valueOf(palceCheck.get(i).get("name").toString())).getShowvalue();
                        return "同一会场的会议时间必须连续性填写，校验出错会场:" + placename + "，第" + palceCheck.get(i).get("sort") + "行";
                    }
                }
            }

        } catch (Exception e) {
            log.error("seepkk-会议日程时间连续性校验异常:", e);
            log.error("seepkk-会议日程时间连续性校验异常:" + startDateList);
            log.error("seepkk-会议日程时间连续性校验异常:" + endDateList);
            log.error("seepkk-会议日程时间连续性校验异常:" + placeList);
            result = "会议日程时间连续性校验异常！-会场时间连续性校验";
            return result;
        }
        return result;
    }

    /**
     * 参会者提名，人员重复选择校验
     */
    public String membersCheck(Map<String, Object> formdata) {
        String result = "";
        List<String> memberList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        try {
            memberList = (List<String>) formdata.get("参会者编号");
            nameList = (List<String>) formdata.get("参会者姓名");
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < memberList.size(); i++) {
                if (nameList.get(i) == null) {
                    continue;
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("member", memberList.get(i));
                map.put("name", nameList.get(i));
                list.add(map);
            }
            Map<Object, List<Map<String, Object>>> dateMap = list.stream().collect(Collectors.groupingBy(t -> MapUtils.getString(t, "member")));
            for (Map.Entry<Object, List<Map<String, Object>>> entry : dateMap.entrySet()) {
                List<Map<String, Object>> dateList = entry.getValue();
                if (dateList.size() > 1) {
                    return "参会者人员不能重复，重复人员:（" + dateList.get(0).get("name") + "）";
                }
            }

        } catch (Exception e) {
            log.error("seepkk-参会者提名人员重复校验异常:", e);
            log.error("seepkk-参会者提名人员重复校验异常:" + memberList);
            result = "seepkk-参会者提名人员重复校验异常！";
            return result;
        }
        return result;
    }

    /**
     * 参会者提名，医生状态校验
     */
    public String membersStateCheck(Map<String, Object> formdata) {
        String result = "";
        List<String> memberList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        try {
            memberList = (List<String>) formdata.get("隐藏-医生状态");
            nameList = (List<String>) formdata.get("参会者姓名");
            for (int i = 0; i < memberList.size(); i++) {
                if (!("验证通过".equals(memberList.get(i)) || "验证中".equals(memberList.get(i)) || "无需验证".equals(memberList.get(i)))) {
                    result = "医生状态必须包含验证通过、验证中、无需验证一种，验证出错人员：" + nameList.get(i);
                }
            }
        } catch (Exception e) {
            log.error("seepkk-参会者提名人员状态校验异常:", e);
            log.error("seepkk-参会者提名人员状态校验异常:" + memberList);
            result = "seepkk-参会者提名人员状态校验异常！";
            return result;
        }
        return result;
    }

    /**
     * 自定义控件 验证
     *
     * @param formBean
     * @param formdata
     * @return
     */
    public String customControlCheck(FormBean formBean, Map<String, Object> formdata) {
        String result = "";
        boolean showValueFlag = true;
        try {
            if (null != formBean.getFieldBeanByDisplay("是否提名HCP")) {
                Long enumHCP = MapUtils.getLong(formdata, formBean.getFieldBeanByDisplay("是否提名HCP").getName());
                log.info("#强生客开,enumHCP：" + enumHCP);
                String showValue = enumItemDAO.findById(enumHCP).getShowvalue();
                showValueFlag = "是".equals(showValue) ? true : false;
            }
            log.info("#强生客开,showValueFlag：" + showValueFlag);
            for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
                if ("5550438035101852361".equals(fieldBean.getInputType())) {
                    String[] controlName = fieldBean.getDisplay().split("_");
                    if (controlName.length > 2) {
                        if (!showValueFlag) {
                            if (controlName[1].equals("参会者身份类别") || controlName[1].equals("科室")) {
                                log.info("#强生客开，HCP 验证跳过。" + controlName[1]);
                                continue;
                            }
                        }

                        String controlValue = MapUtils.getString(formdata, fieldBean.getName());
                        if (null == controlValue || "".equals(controlValue)) {
                            result += "必填项：" + controlName[1] + ",请选择！\n";
                        }
                    }
                }
            }
        } catch (BusinessException e) {
            log.info("#强生客开，自定义控件必填校验错误！ error：", e);
        }
        return result;
    }

    /**
     * 关联底表 自定义控件值查询
     *
     * @param formBean
     * @param params
     * @return
     */
    public Map<String, Object> customControlDataBack(FormBean formBean, Map<String, Object> params) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            StringBuilder sql = new StringBuilder();
            FormTableBean formTableBean = formBean.getMasterTableBean();
            sql.append("select ");
            for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
                if ("5550438035101852361".equals(fieldBean.getInputType())) {
                    String controlValue = formBean.getFieldBeanByDisplay(fieldBean.getDisplay()).getName();
                    sql.append(controlValue + " as " + fieldBean.getDisplay() + ",");
                }
            }
            sql.deleteCharAt(sql.length() - 1); // 去除最后一个参数的 逗号
            sql.append(" from " + formTableBean.getTableName());
            sql.append(" where " + formBean.getFieldBeanByDisplay("活动编号").getName() + "=:activityNo");
            log.info("关联底表数据查询sql：" + sql.toString());
            List<Map> datList = JdbcAgentUtil.doQuery(sql.toString(), params);
            if (!datList.isEmpty()) {
                result = datList.get(0);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("#强生客开 关联底表数据查询错误：", e);
        }
        return result;
    }

    /**
     * 同步MDM医生主数据
     *
     * @param requestjson
     * @return
     */
    public JSONObject syncMDMHcpData(String requestjson) {
        //接口返回值
        JSONObject resultObj = new JSONObject();
        Long batchNbr = UUIDLong.longUUID();
        resultObj.put("batchNbr", batchNbr);//批次号
        int total = 0;
        boolean isSuccess = true;//是否成功调用接口
        boolean hasError = false;//接口返回结果中是否有错误数据项
        String message = "上传成功";
        JSONArray errorAry = new JSONArray();//错误数据
        //解密数据
        String requestData = "";
        DesUtil tools = null;
        try {
            tools = new DesUtil(mdmKey, mdmKey);
            requestData = tools.decode(requestjson);
        } catch (Exception e) {
            log.error("seepkk-同步MDMD医生主数据解密异常", e);
            resultObj.put("isSuccess", false);
            resultObj.put("hasError", hasError);
            resultObj.put("message", "seepkk-同步MDMD医生主数据解密异常");
            resultObj.put("total", total);
            resultObj.put("data", "");
            return resultObj;
        }
        JSONObject dataObj = JSONObject.parseObject(requestData);
        JSONArray dataAry = dataObj.getJSONArray("data");
        //同步数据到MDM医生主数据底表
        for (int i = 0; i < dataAry.size(); i++) {
            JSONObject obj = dataAry.getJSONObject(i);
            try {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("创建时间MDM", obj.get("createTime"));
                map.put("医生科室", obj.get("department"));
                map.put("医生性别", obj.get("gender"));
                map.put("医生主数据编号", obj.get("hcpCode"));
                map.put("医生姓名", obj.get("hcpName"));
                map.put("医院编号", obj.get("hospitalCode"));
                map.put("医院级别", obj.get("hospitalLevel"));
                map.put("医院名称", obj.get("hospitalName"));
                map.put("医院省市", obj.get("hospitalProvince"));
                map.put("是否多点执业", obj.get("isMulti"));
                map.put("是否讲师", obj.get("isSpeaker"));
                map.put("医师执照", obj.get("license"));
                map.put("数据修改时间", obj.get("modifiedDate"));
                map.put("多点执业编号", obj.get("multicode"));
                map.put("操作状态", obj.get("operationType"));
                map.put("医生职称", obj.get("professionalTitle"));
                map.put("验证不通过原因", obj.get("reason"));
                map.put("医生来源系统的id", obj.get("sourceId"));
                map.put("医生来源系统", obj.get("sourceSystem"));
                map.put("讲师级别", obj.get("speakerLevel"));
                map.put("讲师年限", obj.get("speakerYear"));
                map.put("医生状态", obj.get("status"));
                map.put("原始关联医生code", obj.get("oriHcpCode"));
                map.put("原始多点执业编号", obj.get("OriHCPMultiCode"));
                map.put("是否隐藏", obj.get("isHide"));
                map.put("批号", batchNbr);
                //根据医生编号查询数据是否存在
                FlipInfo flipInfo = new FlipInfo(1, 20);
                FormBean bean = formApi4Cap4.getFormByFormCode(Constants.mdmFormCode);
                Map<String, Object> where = new HashMap<String, Object>();
                where.put(bean.getFieldBeanByDisplay("医生主数据编号").getName(), obj.get("hcpCode"));
                List<FormDataMasterBean> masterList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, where);
                if (CollectionUtils.isEmpty(masterList)) {//新增
                    kkBaseFormManager.saveUnflowData(Constants.mdmFormCode, Constants.createUser, map);
                    total++;
                } else {//修改
                    FormDataMasterBean dataBean = masterList.get(0);
                    kkBaseFormManager.updateFormData(Constants.mdmFormCode, masterList.get(0), map);
                    total++;
                }
            } catch (Exception e) {
                log.error("seepkk-同步MDMD医生主数据插入数据失败", e);
                hasError = true;
                message = "上传数据有错误项";
                obj.put("ErrorMsg", e.toString());
                errorAry.add(obj);
            }
        }
        resultObj.put("isSuccess", isSuccess);
        resultObj.put("hasError", hasError);
        resultObj.put("message", message);
        resultObj.put("total", total);
        resultObj.put("data", tools.encode(errorAry.toString()));
        log.info("seepkk-同步MDMD医生主数据:" + resultObj);
        return resultObj;
    }

    /**
     * 表单转word控件附件下载，转换PDF上传系统
     *
     * @param subreference
     * @param savePath
     * @return 附件SubReference
     * @throws Exception
     */
    public Long wordToPdf(Long subreference, Long summaryId) throws Exception {
        List<Long> attachmentlist = this.attachmentManager.getBySubReference(subreference);
        String savePath = StringUtils.substringBefore(AppContext.getCfgHome().toString(), "WEB-INF") + File.separator + "ddkkfile" + File.separator + subreference + File.separator;
        if (!attachmentlist.isEmpty()) {
            String fileUrl = attachmentlist.get(0).toString();
            String fileName = this.attachmentManager.getAttachmentByFileURL(attachmentlist.get(0)).getFilename();
            if (!new File(savePath).exists()) {
                new File(savePath).mkdirs();
            }
            FileOutputStream out = new FileOutputStream(savePath + fileName);
            FileDownloadExporter downloadExporter = new FileDownloadExporter();
            downloadExporter.processDownload(fileUrl, out);
            out.close();
            String pdffileName = StringUtils.substringBefore(fileName, ".") + ".pdf";
            WordToPDF.wordToPDF(savePath + fileName, savePath + pdffileName);
            //上传附件并挂载到表单上
            FileUploadExporter uploadExporter = new FileUploadExporter();
            String fileurlsy = uploadExporter.processUpload(Constants.createUser, new String[]{savePath + pdffileName});
            V3XFile vfile = fileManager.getV3XFile(Long.valueOf(fileurlsy));
            //表单附件框挂载的id
            Long attId = UUIDLong.longUUID();
            Attachment att = new Attachment(vfile);
            att.setReference(summaryId);
            att.setCategory(66);
            att.setSubReference(attId);
            att.setIdIfNew();
            attachmentDAO.save(att);
            return attId;
        }
        return null;
    }

    /**
     * 参会者提名科室 数据校验
     *
     * @param formBean
     * @param formdata
     * @return
     */
    public String isCheckMeeting(FormBean formBean, Map<String, Object> formdata, FormTableBean formTableBean, Map<String, Object> formData) {
        String result = "";
        try {
            // TODO 参会者提名 数据校验
            List<String> department = (List<String>) formdata.get("参会者职称");
            List<String> title = (List<String>) formdata.get("参会者科室");
            List<String> memberName = (List<String>) formdata.get("参会者姓名");
            List<Map<String, Object>> doctorInfo = Lists.newArrayList();
            log.info("#强生客开,参会者职称：" + JSONArray.toJSONString(department));
            log.info("#强生客开,参会者科室：" + JSONArray.toJSONString(title));
            log.info("#强生客开,参会者姓名：" + JSONArray.toJSONString(memberName));
            for (int i = 0; i < department.size(); i++) {
                if (null != department.get(i) && !"".equals(department.get(i))) {
                    Map<String, Object> tempMap = Maps.newHashMap();
                    tempMap.put("zc", department.get(i));
                    tempMap.put("ks", title.get(i));
                    doctorInfo.add(tempMap);
                }
            }
            log.info("#强生客开，参会者提名doctorInfo：" + JSONArray.toJSONString(doctorInfo));

            String enumShowValue = "";
            // 获取表单所有下拉多选自定义控件数据
            for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
                if ("5550438035101852361".equals(fieldBean.getInputType())) {
                    String[] controlName = fieldBean.getDisplay().split("_");
                    if (controlName.length > 2) {
                        String controlValue = MapUtils.getString(formData, fieldBean.getName());
                        if (null == controlValue) continue;
                        String[] values = {};
                        if (-1 != controlValue.indexOf(",")) {
                            values = controlValue.split(",");
                            for (int i = 0; i < values.length; i++) {
                                enumShowValue += this.enumItemDAO.findById(Long.parseLong(values[i])).getShowvalue() + ",";
                            }
                        } else {
                            enumShowValue += this.enumItemDAO.findById(Long.parseLong(controlValue)).getShowvalue() + ",";
                        }
                    }
                }
            }

            // 数据校验
            String[] enumShowValues = enumShowValue.split(",");
            if (doctorInfo.size() == 0) {
                result = "";
            }
            int num = 0;
            for (int i = 0; i < doctorInfo.size(); i++) {
                result += "参会者提名" + memberName.get(i);
                for (Map.Entry<String, Object> entry : doctorInfo.get(i).entrySet()) {
                    if (!ArrayUtils.contains(enumShowValues, entry.getValue())) {
                        result += "," + entry.getValue();
                        num++;
                    }
                }
                result += "不符合标准！";
            }

            if (num == 0) {
                result = "";
            }

        } catch (BusinessException e) {
            log.info("#参会者提名错误：", e);
        }
        return result;
    }

    /**
     * 会议日程提供者校验
     *
     * @param formBean
     * @param formdata
     * @param formDataMasterBean
     * @return
     */
    public String isCheckProvider(FormBean formBean, Map<String, Object> formData, FormDataMasterBean formDataMasterBean, Map<String, Object> formdata) throws BusinessException {


        // 获取主表数据
        List<String> doctorNos = (List<String>) formdata.get("提供者编号");
        List<String> serviceType = (List<String>) formdata.get("服务类型");
        List<String> speakerType = (List<String>) formdata.get("讲者类别");
        List<String> doctorName = (List<String>) formdata.get("提供者");
        log.info("#强生客开,提供者编号：" + JSONArray.toJSONString(doctorNos));
        log.info("#强生客开,提供者：" + JSONArray.toJSONString(doctorName));
        log.info("#强生客开,服务类型：" + JSONArray.toJSONString(serviceType));
        log.info("#强生客开,讲者类别：" + JSONArray.toJSONString(speakerType));
        List<Map<String, Object>> doctorInfo = Lists.newArrayList();
        for (int i = 0; i < doctorNos.size(); i++) {
            if (null != doctorNos.get(i) && !"".equals(doctorNos.get(i))) {
                doctorInfo.add(getProviderInfo(doctorNos.get(i)));
            } else {
                doctorInfo.add(Maps.newHashMap());
            }
        }

        String enumShowValue = "";
        // 获取表单所有下拉多选自定义控件数据
        for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
            if ("5550438035101852361".equals(fieldBean.getInputType())) {
                String[] controlName = fieldBean.getDisplay().split("_");
                if (controlName.length > 2) {
                    String controlValue = MapUtils.getString(formData, fieldBean.getName());
                    if (null == controlValue) continue;
                    String[] values = {};
                    if (-1 != controlValue.indexOf(",")) {
                        values = controlValue.split(",");
                        for (int i = 0; i < values.length; i++) {
                            enumShowValue += this.enumItemDAO.findById(Long.parseLong(values[i])).getShowvalue() + ",";
                        }
                    } else {
                        enumShowValue += this.enumItemDAO.findById(Long.parseLong(controlValue)).getShowvalue() + ",";
                    }
                }
            }
        }
        String result = "";
        String[] enumShowValues = enumShowValue.split(",");
        log.info("doctorInfo.size()：" + doctorInfo.size());
        log.info("doctorInfo:" + JSONArray.toJSONString(doctorInfo));
        if (doctorInfo.size() == 0) {
            result = "";
        }

        int num = 0;
        for (int i = 0; i < doctorInfo.size(); i++) {
            result += "日程中讲者" + doctorName.get(i);
            for (Map.Entry<String, Object> entry : doctorInfo.get(i).entrySet()) {
                if (!ArrayUtils.contains(enumShowValues, entry.getValue())) {
                    result += "," + entry.getValue();
                    num++;
                }
            }
            result += "不符合标准！";
        }

        if (num == 0) {
            result = "";
        }
        return result;
    }

    /**
     * @param startIO     起始IO号
     * @param endIO       结束IO号
     * @param companyCode 公司代码
     * @return
     */
    public String ioCreate(String startIO, String endIO, String companyCode) {
        try {
            FormBean bean = formApi4Cap4.getFormByFormCode(Constants.IOformCode);
            FormTableBean masterTableBean = bean.getMasterTableBean();
            List<BigInteger> ioList = new ArrayList<BigInteger>();
            boolean isContinue = true;
            BigInteger ioNum = new BigInteger(startIO);
            while (isContinue) {
                if (ioNum.compareTo(new BigInteger(endIO)) == 1) {
                    isContinue = false;
                    continue;
                }
                //判断IO号是否已经存在
                FlipInfo flipInfo = new FlipInfo(1, 20);
                Map<String, Object> where = new HashMap<String, Object>();
                where.put(bean.getFieldBeanByDisplay("IO号").getName(), ioNum.toString());
                List<FormDataMasterBean> ioNumList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, where);
                if (!ioNumList.isEmpty()) {
                    isContinue = false;
                    return ioNum.toString() + "已创建，请重新填写起始范围！";
                }
                ioList.add(ioNum);
                ioNum = ioNum.add(new BigInteger("1"));
            }

            //查询目前最大排序号
            String sql = "select top 1 " + masterTableBean.getFieldBeanByDisplay("序号").getName() + " as sort from " + masterTableBean.getTableName() + "  ORDER BY "
                    + masterTableBean.getFieldBeanByDisplay("序号").getName() + " desc";
            List<Map> sorgList = JdbcAgentUtil.doQuery(sql, null);
            int sort = sorgList.isEmpty() ? 0 : MapUtils.getInteger(sorgList.get(0), "sort");
            for (int i = 0; i < ioList.size(); i++) {
                sort = sort + 1;
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("序号", sort);
                map.put("IO号", ioList.get(i).toString());
                map.put("IO号状态", "未使用");
                map.put("公司代码", companyCode);
                kkBaseFormManager.saveUnflowData(Constants.IOformCode, Constants.createUser, map);
            }
        } catch (Exception e) {
            log.error("seepkk-IO号批量生成异常：", e);
            return "IO号生成异常，请联系管理员" + e.toString();
        }
        return "success";
    }

    /**
     * 获取提供者编号 人员数据
     *
     * @param doctorNo 医生编号
     * @return 科室、级别
     */
    public Map<String, Object> getProviderInfo(String doctorNo) {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        try {
            Map<String, Object> params = com.google.common.collect.Maps.newHashMap();
            params.put("doctorNo", doctorNo);
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.mdmFormCode);
            StringBuilder sql = new StringBuilder();
            FormTableBean formTableBean = formBean.getMasterTableBean();
            sql.append("select ");
            sql.append(formBean.getFieldBeanByDisplay("医生科室").getName() + " as ks, ");
            sql.append(formBean.getFieldBeanByDisplay("讲师级别").getName() + " as jb");
            sql.append(" from " + formTableBean.getTableName());
            sql.append(" where " + formBean.getFieldBeanByDisplay("医生主数据编号").getName() + "=:doctorNo ");
            log.info("#强生客开，提供者发起前校验 SQL:" + sql.toString());
            List<Map> datList = JdbcAgentUtil.doQuery(sql.toString(), params);
            if (!datList.isEmpty()) {
                result = datList.get(0);
            }
        } catch (Exception e) {
            log.error("#强生客开，提供者发起前校验错误！", e);
        }
        return result;
    }

    /**
     * 同步参会者提名医生状态同步
     */
    public void syncAttend() {
        //log.info("seepkk-MDM医生数据底表与参会者提名中的医生状态同步开始");
        try {
            //获取参会者提名参会者重复表数据，与MDM医生主数据底表状态同步
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.seepAttend);
            FormBean mdmFormBean = formApi4Cap4.getFormByFormCode(Constants.mdmFormCode);
            StringBuilder sql = new StringBuilder();
            FormTableBean formTableBean = new FormTableBean();
            List<FormTableBean> formTableBeanList = formBean.getSubTableBean();
            for (FormTableBean formTableBean2 : formTableBeanList) {
                if ("参会者明细".equals(formTableBean2.getDisplay())) {
                    formTableBean = formTableBean2;
                }
            }
            FormTableBean mdmFormTableBean = mdmFormBean.getMasterTableBean();
            sql.append("update f set ");
            sql.append(" f." + formBean.getFieldBeanByDisplay("隐藏-参会者医生状态").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("隐藏-医生状态").getName());
            sql.append(",f." + formBean.getFieldBeanByDisplay("参会者职称").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("医生职称").getName());
            sql.append(",f." + formBean.getFieldBeanByDisplay("参会者医院").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("医院名称").getName());
            sql.append(",f." + formBean.getFieldBeanByDisplay("参会者科室").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("医生科室").getName());
            sql.append(",f." + formBean.getFieldBeanByDisplay("参会者医院级别").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("医院级别").getName());
            sql.append(" from " + formTableBean.getTableName() + " f," + mdmFormTableBean.getTableName() + " fm");
            sql.append(" where f." + formBean.getFieldBeanByDisplay("参会者编号").getName() + "=fm." + mdmFormBean.getFieldBeanByDisplay("医生主数据编号").getName());
            sql.append(" and f." + formBean.getFieldBeanByDisplay("隐藏-参会者医生状态").getName() + " is not null ");
            sql.append(" and f." + formBean.getFieldBeanByDisplay("隐藏-参会者医生状态").getName() + " !='医生有效' ");
            sql.append(" and f." + formBean.getFieldBeanByDisplay("隐藏-参会者医生状态").getName() + " !='无需验证' ");
            sql.append(" and f." + formBean.getFieldBeanByDisplay("隐藏-参会者医生状态").getName() + " !=fm." + mdmFormBean.getFieldBeanByDisplay("隐藏-医生状态").getName());
           log.info("seepkk-参会者医生相关信息同步:" + sql.toString());
            List list = new ArrayList();
            JdbcAgentUtil.doUpdateOrInsert(sql.toString(), list);
        } catch (BusinessException e) {
            log.error("seepkk-参会者医生状态同步异常:", e);
        }
        //log.info("seepkk-MDM医生数据底表与参会者提名中的医生状态同步结束");
    }


    public FreemarkFlowManager getFreemarkFlowManager() {
        return freemarkFlowManager;
    }


    public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
        this.freemarkFlowManager = freemarkFlowManager;
    }


    public FormApi4Cap4 getFormApi4Cap4() {
        return formApi4Cap4;
    }


    public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
        this.formApi4Cap4 = formApi4Cap4;
    }


    public String getMdmKey() {
        return mdmKey;
    }

    public void setMdmKey(String mdmKey) {
        this.mdmKey = mdmKey;
    }

}